<template>
  <a-modal
    style="width: 50%"
    :title="titleMap[mode]"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :destroyOnClose="true"
    @cancel="handleCancel"
    :maskClosable="false">
    <div style="margin-top: 12px;min-height: 300px;min-width: 650px">
      <a-form-model ref="ruleAddForm" :model="addForm" :rules="addRules" >
        <a-form-model-item ref="name" label="角色名称" prop="name" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input v-model="addForm.name" placeholder="请输入角色名称" :max-length="40"></a-input>
        </a-form-model-item>
        <a-form-model-item label="描述信息" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-textarea :rows="4" v-model.trim="addForm.description" placeholder="请输入描述信息" :max-length="255" />
        </a-form-model-item>
        <!-- <a-form-model-item ref="permissionIds" label="分配权限" prop="permissionIds" style="float: left;width: 100%;"
          :wrapper-col="{ span: 20 }" :labelCol="{ span: 3 }">
          <a-tree-select :replaceFields="replaceFields" :default-expanded-keys="Ids" :default-selected-keys="Ids"
            :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }" tree-checkable tree-default-expand-all
            :tree-data="treeData" :max-tag-count="10" tree-node-filter-prop="name" placeholder="请选择分配的权限"
            v-model="addForm.permissionIds" @change="onChange">
          </a-tree-select>
        </a-form-model-item> -->
        <a-form-model-item
          ref="permissionIds"
          label="分配权限"
          prop="permissionIds"
          :label-col="labelCol"
          :wrapper-col="wrapperCol">
          <a-spin :spinning="treeOnLoad">
            <a-tree
              v-if="!treeOnLoad"
              :tree-data="treeData"
              draggable
              blockNode
              :replaceFields="replaceFields"
              checkable
              @check="treeSelect"
              v-model:selectedKeys="selectedKeys"
              v-model:checkedKeys="checkedKeys">
              <template v-slot:title="nodeData">
                <div>{{ nodeData.name }}</div>
              </template>
            </a-tree>
          </a-spin>
        </a-form-model-item>
      </a-form-model>
    </div>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button type="primary" :visible="visibleBtn" :loading="loadingBtn" @click="handleOk">
        保存
      </a-button>
    </template>
  </a-modal>
</template>
<script>

import { detailRoles, addRoles, editRoles } from '@/api/lessee'
import { getTree } from '@/api/login'

//  getStorageIds, getSelectedItem, ToTree,
import { lookId } from '@/utils/util'

export default {
  components: {},
  data () {
    const checkNode = (rule, value, callback) => {
      if (this.checkedKeys.length == 0) {
        callback(new Error('请分配权限'))
      } else {
        callback()
      }
    }
    return {
      addRules: {
        permissionIds: [
          { required: true, message: '请选择权限!', validator: checkNode }
        ],
        name: [
          { required: true, message: '请输入角色名称!', trigger: 'blur' }
        ]
      },
      replaceFields: { children: 'children', label: 'name', value: 'permissionId', key: 'permissionId' },
      addForm: {
        name: '',
        description: '',
        permissionIds: null
      },
      // 权限树
      treeData: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visible: false,
      confirmLoading: false,
      loading: false,
      visibleBtn: false,
      loadingBtn: false,
      mode: 'add',
      titleMap: {
        add: '新增',
        edit: '编辑'
      },
      rowData: '',
      Ids: null,
      defaultValue: null,
      editPermissions: '',

      treeOnLoad: true,
      selectedKeys: [],
      checkedKeys: [],
      allSelectedNodes: []
    }
  },
  methods: {
    treeSelect (selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.checkedKeys = selectedKeys
      // 已勾选子节点以及半勾选状态的父节点
      this.allSelectedNodes = selectedKeys.concat(info.halfCheckedKeys)
    },
    // onChange(checkedKeys) {
    //   let arr = checkedKeys
    //   if (checkedKeys.length > 0) {
    //     let arrChecked = []
    //     for (let i = 0; i < checkedKeys.length; i++) {
    //       arrChecked.push(getSelectedItem(checkedKeys[i], this.treeData))
    //     }
    //     arrChecked = [...new Set(arrChecked)]
    //     arr = arr.concat(arrChecked)
    //   }
    //   this.Ids = arr

    // },
    // 显示
    open (mode = 'add') {
      this.mode = mode
      this.visible = true
      if (this.mode == 'add') {
        getTree().then(r => {
          this.treeOnLoad = false
          if (r.code == 200) {
            this.treeData = r.data
          }
        })
      }
      return this
    },

    // 获取行数据和id
    setData (row) {
      this.rowData = row
      if (this.mode == 'edit') {
        detailRoles(row.roleId).then(res => {
          if (res.code == 200) {
            this.addForm = res.data
            // if (res.data.permissions.length > 0) {
            // this.editPermissions = res.data.permissions
            // //提取详情中权限的页面
            // let arr1 = getStorageIds(res.data.permissions);
            getTree().then(r => {
              this.treeOnLoad = false
              if (r.code == 200) {
                this.treeData = r.data
                if (res.data.permissions.length > 0) {
                  // this.selectedKeys = lookId(res.data.permissions, 'allChildrenId')

                  this.selectedKeys = lookId(res.data.permissions, 'operation')
                  this.checkedKeys = this.selectedKeys
                  // this.allSelectedNodes = lookId(res.data.permissions)
                  this.allSelectedNodes = this.selectedKeys
                }
                // this.treeData = ToTree(r.data);
                // if (this.editPermissions.length > 0) {
                //   this.editPermissions = this.treeData.filter((x) => {
                //     let item = this.editPermissions.some((i) => i.permissionId == x.permissionId)
                //     return item
                //   });
                //   // 提取权限树中的页面
                //   let arr2 = getStorageIds(this.editPermissions)
                //   //获取数组的交集
                //   this.Ids = arr1.filter(function (val) { return arr2.indexOf(val) > -1 })
                //   this.addForm.permissionIds = this.Ids
                // }
              }
            })

            // let permissions = res.data.permissions
            // permissions = permissions.map(item => {
            //   return item.permissionId
            // })
            // this.addForm.permissionIds=permissions
            // this.Ids = permissions.join(",")
            // permissions = this.treeData.filter((x) => {
            //   let item = permissions.some((i) => i.permissionId == x.permissionId)
            //   return item
            // });
            // this.Ids = permissions.map((item, index) => {
            //   return item.permissionId
            // })
            // this.addForm.permissionIds = this.Ids
            // console.log(permissions)
            // this.addForm.permissionIds = this.Ids
            // permissions = permissions.map(item => {
            //   return item.permissionId
            // })
            // this.addForm.permissionIds=permissions
            // this.Ids = permissions
            // }
          }
        })
      }
    },

    // 关闭
    handleCancel () {
      this.visible = false
      this.loadingBtn = false
      this.visibleBtn = false
      this.$emit('close')
    },
    // 确认
    handleOk () {
      this.loadingBtn = true
      this.visibleBtn = true
      this.$refs.ruleAddForm.validate(valid => {
        if (valid) {
          const par = {
            name: this.addForm.name,
            description: this.addForm.description,
            permissionIds: this.allSelectedNodes
          }
          if (this.mode == 'edit') par.roleId = this.addForm.roleId
          const Api = this.mode == 'add' ? addRoles : editRoles
          Api(par).then(res => {
            if (res.code === 200) {
              this.$notification['success']({
                message: '提示',
                description: '保存成功！',
                duration: 8
              })
              this.visible = false
              this.$emit('success')
            } else {
              this.$notification['error']({
                message: '提示',
                description: res.message,
                duration: 8
              })
            }
            this.visibleBtn = false
            this.loadingBtn = false
          })
        } else {
          this.loadingBtn = false
          this.visibleBtn = false
          return false
        }
      })
    }
  }
}
</script>
<style scoped lang="less" >
/deep/ .ant-modal-content {
  position: relative;
  background-color: #fff;
  background-clip: padding-box;
  border: 0;
  border-radius: 2px;
  pointer-events: auto;
  max-width: 1000px;
  display: inline-block;
}
</style>
